<template>
  <div id="reg">
    <div v-if="showReg">
      <div class="reg">
        <group title="" class="weui-cells_form">
          <x-input v-model="formItem.phone" type="tel" title="手机号" class="weui-vcode" placeholder="请输入手机号" :max="11" :show-clear="false">
            <x-button :disabled="disabled" slot="right" type="primary" mini @click.native="sendCode">{{codebtn}}</x-button>
          </x-input>
          <x-input v-model="formItem.code" type="tel" title="验证码" class="weui-vcode" placeholder="请输入短信验证码" :max="4"></x-input>
          <x-input v-model="formItem.password" type="password" title="新密码" class="weui-vcode" placeholder="请输入密码(6~16位)" :max="16" :min="6"></x-input>
          <x-input v-model="formItem.inviter_id" type="tel" :max="11" title="推荐人手机号" class="weui-vcode" placeholder="选填"></x-input>
        </group>
      </div>
      <div style="margin: 0.3rem 0.2rem 0.2rem 0.2rem">
        <x-button type="primary" :show-loading="loading" action-type="button" @click.native="handleReg">{{btn}}</x-button>
      </div>
      <p style="text-align: center; font-size: 0.25rem;">
        <i class="icon icon-check text-orange" style="font-size: 0.3rem"></i>
        我同意<span class="text-orange">《途鸟配送服务协议》</span>
      </p>
    </div>
    <div id="container2" style="display: none;"></div>
  </div>
</template>
<script>
import PubHeader from '../components/PubHeader.vue'
import { checkTel } from '../libs/fn'
export default{
  components: {
    PubHeader
  },
  mounted() {
    var regmap, geolocation;
    //加载地图，调用浏览器定位服务
    regmap = new AMap.Map('container2', {
      resizeEnable: true
    });
    regmap.plugin('AMap.Geolocation', () => {
      geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 60000,          //超过10秒后停止定位，默认：无穷大
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        buttonPosition:'RB'
      });
      regmap.addControl(geolocation);
      geolocation.getCurrentPosition();
      AMap.event.addListener(geolocation, 'complete', (data) => {
        this.showReg = true
        this.formItem.location = data.formattedAddress
        this.formItem.lat = data.position.lat
        this.formItem.lng = data.position.lng
        this.formItem.city_code = data.addressComponent.adcode
      });
      AMap.event.addListener(geolocation, 'error', (data) => {
        let errorMsg = data.info == 'FAILED'? '途鸟未获取到您的定位权限，不能完成注册，请到设置中开启': '您的浏览器不支持定位，不能注册'

        this.formItem.location = '珍珠路36号'
        this.formItem.lat = 30.711303
        this.formItem.lng = 111.286304
        this.formItem.city_code = '420502'
        this.showReg = true

        // this.$vux.confirm.show({
        //   title: '<i class="icon icon-gantanhao"></i>',
        //   content: errorMsg,
        //   confirmText: '刷新',
        //   cancelText: '返回',
        //   onCancel: () => {
        //     this.$router.go(-1)
        //   },
        //   onConfirm: () => {
        //     window.location.reload()
        //   }
        // })
      });
    });

  },
  data() {
      return {
        showReg: false,
        loading: false,
        disabled: false,
        btn: '注册',
        codebtn: '发送验证码',
        formItem: {
          phone: '',
          client: $config.client_type,
          device: $config.device_type,
          version: $config.version,
          password: '',
          code: '',
          os: 'wap',
          lat: '',
          lng:'',
          location: '',
          city_code: '',
          inviter_id: '',
          open_id: '',
          device_code: 'wap',
          device_name: 'wap'
        }
      }
  },
  methods: {
    sendCode() {
      if(!checkTel(this.formItem.phone)) {
        this.$vux.toast.text('手机号码格式不正确', 'middle')
        return false
      }
      this.disabled = true
      this.codebtn = '正在发送...'
      this.$http.post($config.host + '/api/Userbase/getMessage', qs.stringify({
        phone: this.formItem.phone,
        type: 1
      })).then((res) => {
        const {code, msg} = res.data
        if(code == 1) {
          let i = $config.sendCodeTimer
          let timer = setInterval(() => {
            i--
            this.codebtn = i+'s发送成功'
            if(i <= 0) {
              clearInterval(timer)
              this.disabled = false
              this.codebtn = '重新发送'
            }
          }, 1000)
        } else {
          this.disabled = false
          this.codebtn = '获取验证码'
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch((err) => {
        this.disabled = false
        this.codebtn = '获取验证码'
        this.$vux.toast.text($config.errMsg, 'middle')
      })


    },
    handleReg() {
      if(!checkTel(this.formItem.phone)) {
        this.$vux.toast.text('手机号码格式不正确', 'middle')
        return false
      }
      if(this.formItem.code.length < 4) {
        this.$vux.toast.text('请填写4位验证码', 'middle')
        return false
      }
      if(this.formItem.password.length < 6 || this.formItem.password.length > 16) {
        this.$vux.toast.text('请填写6~16位密码', 'middle')
        return false
      }
      if(!checkTel(this.formItem.inviter_id) && this.formItem.inviter_id) {
        this.$vux.toast.text('推荐人手机号格式不正确', 'middle')
        return false
      }

      this.loading = true
      this.btn = '正在注册中'
      this.$http.post($config.host + '/api/Userbase/register', qs.stringify(this.formItem)).then((res) => {
        const {code, msg} = res.data
        if(code == 1){
          this.$vux.toast.text(msg, 'middle')
          this.$router.push('login')
        } else {
          this.loading = false
          this.btn = '重新注册'
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch((err) => {
        this.loading = false
        this.btn = '重新注册'
        this.$vux.toast.text($config.errMsg, 'middle')
      })
    }
  },
  beforeRouteLeave(to, from, next) {
    this.formItem = {
      phone: '',
      client: $config.client_type,
      device: $config.device_type,
      version: $config.version,
      password: '',
      code: '',
      os: 'wap',
      lat: '',
      lng:'',
      location: '',
      city_code: '',
      inviter_id: '',
      open_id: '',
      device_code: 'wap',
      device_name: 'wap'
    }

    next()
  }
}
</script>
<style scoped>
  .reg{
    margin: 0.2rem;
    background: #fff;
    height: auto;
    box-shadow: 0px 0px 0.15rem rgba(0, 0, 0, 0.07);
  }
</style>
